package com.mo.modular.auth.util;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {

	public static int str2Ip(String ip) throws Exception {
		InetAddress address = InetAddress.getByName(ip);
		byte[] bytes = address.getAddress();
		int a, b, c, d;
		a = byte2int(bytes[0]);
		b = byte2int(bytes[1]);
		c = byte2int(bytes[2]);
		d = byte2int(bytes[3]);
		int result = (a << 24) | (b << 16) | (c << 8) | d;
		return result;
	}
	
	public static long ip2long(String ip) throws Exception {
		int ipNum = str2Ip(ip);
		return int2long(ipNum);
	}

	public static long int2long(int i) {
		long l = i & 0x7fffffffL;
		if (i < 0) {
			l |= 0x080000000L;
		}
		return l;
	}
	
	public static int byte2int(byte b) {
		int l = b & 0x07f;
		if (b < 0) {
			l |= 0x80;
		}
		return l;
	}
	

	public static String getRemoteIpAddr(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(isValidIpAddr(ip)){
			return ip.split(",")[0];
		}
		
		ip = request.getHeader("Proxy-Client-IP");
		if(isValidIpAddr(ip)){
			return ip;
		}
		
		ip = request.getHeader("WL-Proxy-Client-IP");
		if(isValidIpAddr(ip)){
			return ip;
		}
		
		ip = request.getHeader("HTTP_CLIENT_IP");
		if(isValidIpAddr(ip)){
			return ip;
		}
		
		return request.getRemoteAddr();
	}

	private static boolean isValidIpAddr(String ip){
		return ip != null && !ip.isEmpty() && !ip.equalsIgnoreCase("unknown");
	}

}
